//
//  AVPlayerManger.m
//  BLDMusics
//
//  Created by lxd on 16/3/19.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "AVPlayerManger.h"

@interface AVPlayerManger ()

@property (nonatomic, assign) CGFloat musicDuration; // 要播放的音乐时长


@end

@implementation AVPlayerManger

+ (AVPlayerManger *)shareplayer {
    // 静态修饰指针
    static AVPlayerManger *manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[AVPlayerManger alloc] init];
        if (!manger.audioPlayer) {
            manger.audioPlayer = [[AVPlayer alloc] init];
        }
        
    });
    return manger;
}


- (void)playWithUrl:(NSString *)url {
    
    // 保证没有url时不创建播放项目， 确保安全
    if (!url) {
        return;
    }
    // 如果当前正在播放，则移除监听
    if (self.audioPlayer.currentItem) {
//        [self.audioPlayer.currentItem removeObserver:self forKeyPath:@"Music"];
    }
    
    // 创建播放项目
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    // 替换当前播放项目
    [self.audioPlayer replaceCurrentItemWithPlayerItem:playerItem];
    
    self.isPlaying = YES;
    
    if ([DSYPlayerTool sharePlayerTool].isPlaying == YES) {
        [[DSYPlayerTool sharePlayerTool] pause];
        [[PlayViewController sharePlayViewBar] updateView];
    }
    
    
    
    [self.audioPlayer play];
    
    // 监听音乐播放状态
//    [playerItem addObserver:self forKeyPath:@"Music" options:NSKeyValueObservingOptionNew context:nil];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    NSLog(@"播放状态");
//     [self calculate];
    
}



-(void)pause {
    self.isPlaying = NO;
    self.section = -1;
    self.row = -1;
    [self.audioPlayer pause];
    NSLog(@"暂停状态");
}




@end
